<?php
class setting extends base{

	public function init(){ // 公用
		parent::init(); // 这是必须的

		$this->tit = '设置';
		$this->modelObj = D('company');
		$this->upload_fileObj = D('upload_file');
    }

    public function index(){
		if($this->isAjax()){
			$arrBase = array('site','baoxiu','diaocha');
			foreach ($arrBase as $val) {
                $data = $this->postData($val);
                $this->modelObj->set_setting($this->company['id'], $val, $data);
			}
            $this->renderSuccess('更新成功');
		}
		$info = $this->modelObj->get_setting($this->company['id']);
		if($info['site']['site_logo']){
			$info['site']['site_logo'] = $this->upload_fileObj->get_image($info['site']['site_logo']);
        }
		$this->info = $info;
    }
	//清除缓存
	public function cache(){
		if ($this->isAjax()) {
			$data = $this->postData('data');
			// $this->rmCache($this->postData('cache'));
			$site_path = APP_DIR.DS.'protected'.DS."cache/{$this->site['id']}/";
			$this->deleteFolder($site_path);
            return $this->renderSuccess('清除成功');
        }
    }

	public function smsTest($AccessKeyId, $AccessKeySecret, $sign, $msg_type, $template_code, $accept_phone)
    {
        // $SmsDriver = new SmsDriver([
        //     'default' => 'aliyun',
        //     'engine' => [
        //         'aliyun' => [
        //             'AccessKeyId' => $AccessKeyId,
        //             'AccessKeySecret' => $AccessKeySecret,
        //             'sign' => $sign,
        //             $msg_type => compact('template_code', 'accept_phone'),
        //         ],
        //     ],
        // ]);
        // $templateParams = [];
        // if ($msg_type === 'order_pay') {
        //     $templateParams = ['order_no' => '2018071200000000'];
        // }
        // if ($SmsDriver->sendSms($msg_type, $templateParams, true)) {
        //     return $this->renderSuccess('发送成功');
        // }
        // return $this->renderError('发送失败 ' . $SmsDriver->getError());
	}

	/**
     * 递归删除指定目录下所有文件
     * @param $path
     * @return bool
     */
    private function deleteFolder($path)
    {
        if (!is_dir($path))
            return false;
        // 扫描一个文件夹内的所有文件夹和文件
        foreach (scandir($path) as $val) {
            // 排除目录中的.和..
            if (!in_array($val, ['.', '..', '.gitignore', 'index.html'])) {
                // 如果是目录则递归子目录，继续操作
                if (is_dir($path . $val)) {
                    // 子目录中操作删除文件夹和文件
                    $this->deleteFolder($path . $val . '/');
                    // 目录清空后删除空文件夹
                    rmdir($path . $val . '/');
                } else {
                    // 如果是文件直接删除
                    unlink($path . $val);
                }
            }
        }
        return true;
    }

}